package resources

import (
	"errors"
	"os"
	"path/filepath"
	"sort"
)

type Order int

const (
	OrderDefault = Order(iota) + 1
	OrderNameAsc
	OrderNameDesc
	OrderSizeAsc
	OrderSizeDesc
	OrderUpdateTimeAsc
	OrderUpdateTimeDesc
)

// List 获取目录下的文件列表
func (cls *Resources) List(paths []string, order Order) ([]Entry, error) {
	var path, err = cls.normal(paths)
	if nil != err {
		return nil, err
	}

	files, err := os.ReadDir(filepath.Join(cls.path, path))
	if nil != err && !os.IsNotExist(err) {
		return nil, err
	}

	if os.IsNotExist(err) {
		return nil, errors.New("目录不存在")
	}

	var entries []Entry
	for _, item := range files {
		stat, err := item.Info()
		if nil != err {
			return nil, err
		}

		entries = append(entries, Entry{Name: item.Name(), IsDir: item.IsDir(), Size: stat.Size(), UpdateTime: stat.ModTime().Unix()})
	}

	switch order {
	case OrderNameAsc:
		sort.Slice(entries, func(i, j int) bool {
			return entries[i].Name < entries[j].Name
		})
	case OrderNameDesc:
		sort.Slice(entries, func(i, j int) bool {
			return entries[i].Name > entries[j].Name
		})
	case OrderSizeAsc:
		sort.Slice(entries, func(i, j int) bool {
			return entries[i].Size < entries[j].Size
		})
	case OrderSizeDesc:
		sort.Slice(entries, func(i, j int) bool {
			return entries[i].Size > entries[j].Size
		})
	case OrderUpdateTimeAsc:
		sort.Slice(entries, func(i, j int) bool {
			return entries[i].UpdateTime < entries[j].UpdateTime
		})
	case OrderUpdateTimeDesc:
		sort.Slice(entries, func(i, j int) bool {
			return entries[i].UpdateTime < entries[j].UpdateTime
		})
	}

	return entries, nil
}
